package ejb.facades.forum;

import ejb.facades.AbstractFacade;
import entities.User;
import entities.forum.Message;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * Trabalho PD - 2014/2015
 * @author a21210380 a21210392
 */
@Stateless
public class MessageFacade extends AbstractFacade<Message> implements MessageFacadeLocal {
    @PersistenceContext(unitName = "Trabalho_PDPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public MessageFacade() {
        super(Message.class);
    }
    
    @Override
    public List<Message> findReceivedEmails(User user) {
        return em.createNamedQuery("Message.findAllByReceivingUser", Message.class)
                .setParameter("idUser", user.getId())
                .getResultList();
    }
    
    @Override
    public Message findReceivedEmail(User user, int email) {
        List<Message> resultList = em.createNamedQuery("Message.findByReceivingUser", Message.class)
                .setParameter("idUser", user.getId())
                .setParameter("idMessage", email)
                .getResultList();
        if(resultList.isEmpty()) {
            return null;
        } else {
            return resultList.get(0);
        }
    }
}
